#include "StdAfx.h"
#include "ScriptEditorSolutionSerialiser.h"
#include "ScriptEditorSolution.h"
#include "ScriptEditorTabWidget.h"
#include "ScriptEditorWidget.h"
#include <tinyxml.h>

namespace Lit
{
	namespace Editor
	{
		ScriptSolutionSerialiser::ScriptSolutionSerialiser( ) : XmlSerialiser<ScriptSolution>( "AngelScript Solution Serialiser", 1.0 ){}
		ScriptSolutionSerialiser::~ScriptSolutionSerialiser(){}
			
		void ScriptSolutionSerialiser::saveObject( TiXmlDocument * doc, const ScriptSolution& in )
		{
			doc->LinkEndChild(new TiXmlDeclaration(PROJECT_VERSION_STRING, "UTF-8", "true"));
			TiXmlElement* scriptsNode = new TiXmlElement("Solution");
			scriptsNode->SetAttribute("Name", mName.c_str());
			for( auto i=in.getScripts().begin(); i!=in.getScripts().end(); i++ )
			{
				TiXmlElement * el = new TiXmlElement("Script");
				el->SetAttribute("Path", i->get()->getPath().str().c_str() );
				
				el->SetAttribute("IsCurrent", i->get()->isCurrent()?"true":"false");
				
				scriptsNode->LinkEndChild( el );
			}
			doc->LinkEndChild( scriptsNode );
		}
		void ScriptSolutionSerialiser::loadObject( TiXmlDocument * doc, const std::string &base_dir, ScriptSolution& sol )
		{
			TiXmlHandle hDoc(doc);
			TiXmlElement* pElem;
			TiXmlHandle hRoot(0);
			std::string name;
			// block: name
			{
				pElem=hDoc.FirstChildElement("Solution").Element();
				// should always have a valid root but handle gracefully if it does
				if (!pElem) return;
				TiXmlAttribute * atr=pElem->FirstAttribute();
				for( atr; atr; atr=atr->Next() ) if(std::string(atr->Name())=="Name"){ name=atr->Value(); break; }
				// save this for later
				hRoot=TiXmlHandle(pElem);
			}
			if( name.empty() ) throw InvalidParameter( "Name", "missing solution parameter", EXC_LOC );
			sol.prepareUi(name);
			{
				pElem=hRoot.FirstChild( "Script" ).Element();
				for( pElem; pElem; pElem=pElem->NextSiblingElement())
				{
					bool curr=false, isop = false;
					std::string p;
					TiXmlAttribute * attrib = pElem->FirstAttribute();
					for( attrib; attrib; attrib=attrib->Next() )
					{
						std::string name (attrib->Name());
						if(name=="Path")
						{
							p = attrib->Value();
							break;
						}
						else if( name == "IsCurrent" )
						{
							if( std::string(attrib->Value()) == "true" ) curr = true;
							else curr = false;
						}
					}

					ScriptSolutionItemPtr scr(sol.openScript(p));
					if( curr ) scr->setCurrent();
				}
			}
		}
	};
};